package com.xunmall.account.service.impl;

import com.xunmall.account.dto.PermissionDto;
import com.xunmall.account.entity.PermissionDO;
import com.xunmall.account.mapper.PermissionMapper;
import com.xunmall.account.service.PermissionService;
import com.xunmall.base.exception.BadRequestException;
import com.xunmall.base.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: WangYanjing
 * @Date: 2018/12/27 10:53
 * @Description:
 */
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public Boolean checkPermissionCode(String code) {
        PermissionDO entity = new PermissionDO();
        entity.setCode(code);
        List<PermissionDO> entities = permissionMapper.select(entity);
        if (entities.size() > 0) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public PermissionDO create(PermissionDO entity) {
        if (entity == null || StringUtils.isBlank(entity.getCode())) {
            throw new BadRequestException("error.account.0001", this);
        }
        // 校验是否重复
        boolean isUnique = checkPermissionCode(entity.getCode());
        if (!isUnique) {
            throw new BadRequestException("error.account.0004", this, "code");
        }
        entity.buildForInsert();
        int result = permissionMapper.insertSelective(entity);
        if (result > 0) {
            return permissionMapper.selectByPrimaryKey(entity.getUuid());
        } else {
            throw new BadRequestException("error.account.0002", this);
        }
    }

    @Override
    public PermissionDO update(PermissionDO entity) {
        if (entity == null || StringUtils.isBlank(entity.getUuid())) {
            throw new BadRequestException("error.account.0001", this);
        }
        PermissionDO oldEntity = permissionMapper.selectByPrimaryKey(entity.getUuid());
        if (oldEntity == null) {
            throw new BadRequestException("error.account.0003", this);
        }
        BeanUtils.copyProperties(entity, oldEntity);
        oldEntity.buildForUpdate();
        int result = permissionMapper.updateByPrimaryKeySelective(oldEntity);
        if (result > 0) {
            return permissionMapper.selectByPrimaryKey(oldEntity.getUuid());
        } else {
            throw new BadRequestException("error.account.0002", this);
        }
    }

    @Override
    public List<PermissionDto> getByRole(String compId, String roleId) {
        return permissionMapper.getPermissionsByRole(compId, roleId);
    }

    @Override
    public PermissionDO getPermissionByUuid(String uuid) {
        return permissionMapper.selectByPrimaryKey(uuid);
    }

}